// pages/video/video.js
import api from '../../utils/api.js'
const app = getApp();
import { HTTP } from '../../utils/http.js'
import { config } from '../../utils/config'
let http = new HTTP()
var submitS = true
const util = require("../../utils/fenxiang.js");
const stepChinese = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '二十一']
let tabLeft = ['11%', '44%', '78%']
Page({
    /**
     * 页面的初始数据
     */
    data: {
        height: app.globalData.height * 2 + 20,
        allData: {},
        ingredients: null, //配料
        nutrition: null, //营养普
        step: null, // 步骤
        num: 4,
        url: config.imgUrl + "/images/index/xing2.png",
        grade: null, //评分
        authorizeBtn: false,
        stepChinese: stepChinese, //步骤映射中文
        isLeft: '-50%',
        NAV: [0, 1, 2],
        navName: ['营养谱', '用料', '做法'],
        scrollTop: 0, //滚动距离
        isScrolling: false,
        is_auth: false,
        caiId: '', //菜谱id
        numList: [0, 0],
        zList: [], //主料
        fList: [], //辅料
        showFood: true, //显示食材
        isTop: false,
        submit: true,
        showSwiper: false,
        empty: true,
        aLength: 1,
        sameBook: [], //相似菜谱
        has: 0,
        areaInfo: "",
        cookId: 0, //菜品id
        nearBool: true, //周围商家
        recommend: [],
        addressInfo: {
            name: "",
            tel: "",
            add: ""
        },
        findex: 0,
        zbool: true,
        fbool: true,
        iscontent: false,
        booktab: true,
        istuijian: false,
        notuijian: false,
        imgUrl: config.imgUrl,
        showTop: true,
        indexRefresh: false  //返回首页后默认菜谱不刷新
    },
    //授权 初始化
    likesClick() {
        this.setData({
            is_auth: true
        })
    },
    showDifferent(e) {
        console.log()
        var i = e.currentTarget.dataset.index,
            zbool = this.data.zbool,
            fbool = this.data.fbool
        if (i == 0) {
            zbool = true
            fbool = true
        } else if (i == 1) {
            zbool = true
            fbool = false
        } else if (i == 2) {
            zbool = false
            fbool = true
        }
        this.setData({
            findex: i,
            zbool: zbool,
            fbool: fbool
        })
    },
    //点击事件
    choose() {
        wx.navigateTo({
            url: "/pages/getDizhi/getDizhi?order=1",
        })
    },
    shoucang() {
        if (this.data.url == config.imgUrl + "/images/index/xing2.png") {
            http.request({
                url: api.addDelBookCollect,
                method: "POST",
                data: {
                    cookbookId: this.data.allData.id,
                    statusID: 1
                },
                success: (res) => {
                    this.setData({
                        url: config.imgUrl + "/images/index/xing1.png"
                    })
                    wx.showToast({
                        title: '收藏成功',
                        icon: '',
                        mask: true
                    })
                    var list = wx.getStorageSync("shoucang-list2") || [];
                    list.push({
                        cookbookId: this.data.allData.id,
                        userId: wx.getStorageSync("user_id"),
                    })
                    wx.setStorageSync("shoucang-list2", list);
                }
            })
        } else {
            http.request({
                url: api.addDelBookCollect,
                method: "POST",
                data: {
                    cookbookId: this.data.allData.id,
                    statusID: 2
                },
                success: (res) => {
                    this.setData({
                        url: config.imgUrl + "/images/index/xing2.png"
                    })
                    wx.showToast({
                        title: '取消收藏',
                        icon: '',
                        mask: true
                    })
                    var list = wx.getStorageSync("shoucang-list2")
                    var list = list.filter((item) => {
                        return !(item.cookbookId == this.data.allData.id && item.userId == wx.getStorageSync("user_id"))
                    })
                    wx.setStorageSync("shoucang-list2", list);
                }
            })
        }
    },
    /*体验购买*/

    // 点击推荐
    recommend(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: "/pages/video/video?id=" + id
        })
    },
    toMain() {
        if (this.data.num == 0) {
            wx.showToast({
                title: '您还未选菜',
                icon: "none",
                mask: true
            })
        } else {
            wx.navigateTo({
                url: "/pages/recommendShopList/recommendShopList?type=1"
            })
        }
    },

    //编辑食材数量
    editNums(e) {

        let vageId = e.currentTarget.dataset.id
        let vageType = e.currentTarget.dataset.vage
        let handleType = e.currentTarget.dataset.type;
        // 主菜       
        if (vageType == "zList") {
            let zList = this.data.zList;
            // 减去数量
            if (handleType === "sub") {
                zList.forEach(item => {
                    if (item.id == vageId) {
                        if (item.number > 0) {
                            item.number--
                        } else {
                            return false
                        }
                    }
                })
                console.log('zList', zList);
            }
            if (handleType === "add") {
                zList.forEach(item => {
                    if (item.id == vageId) {
                        item.number++
                    }
                })
            }
            this.setData({
                zList
            })
        }

        // 辅材

        if (vageType == "fList") {
            let fList = this.data.fList;
            // 减去数量
            if (handleType === "sub") {
                fList.forEach(item => {
                    if (item.id == vageId) {
                        if (item.number > 0) {
                            item.number--
                        } else {
                            return false
                        }
                    }
                })
                console.log('fList', fList);
            }
            if (handleType === "add") {
                fList.forEach(item => {
                    if (item.id == vageId) {
                        item.number++
                    }
                })
            }
            this.setData({
                fList
            })
        }



    },
    //辅材个数




    //数据编辑
    editGoods(obj, url) {
        return new Promise((resolve, reject) => {
            http.request({
                url: url,
                data: obj,
                success: res => {
                    resolve(res);
                }
            })
        })
    },
    //页面切换
    cookShow() {
        // if (this.data.cookBool == "购买食材") {
        //     this.setData({
        //         showFood: true,
        //         cookBool: "查看做法"
        //     })
        // } else {
        //     this.setData({
        //         showFood: false,
        //         cookBool: "购买食材"
        //     })

        // }
        // 锚点跳转
        const query = wx.createSelectorQuery()
        query.select('.buzhou').boundingClientRect()
        query.selectViewport().scrollOffset()
        query.exec(function (res) {
            res[0].top // #the-id节点的上边界坐标
            res[1].scrollTop // 显示区域的竖直滚动位置
            let distance = res[0].top + res[1].scrollTop - 80
            wx.pageScrollTo({
                scrollTop: distance
            })
        })

    },
    add() {
        if (!wx.getStorageSync("address")) {
            app.login();
            return
        }
        var listMenus = wx.getStorageSync('select-menus') || [];
        for (let v of listMenus) {
            if (v.id == this.data.allData.id) {
                wx.showToast({
                    title: '请不要重复添加',
                    icon: 'none',
                    duration: 1500,
                    mask: true
                })
                return false;
            }
        }
        console.log(this.data.allData)
        listMenus.push({
            flag: true,
            id: this.data.allData.id,
            name: this.data.allData.name,
            main_img_url: this.data.allData.url,
            ingredients: [],
            count: this.data.allData.count,
            time: this.data.allData.cookt,
            seasoning_count: this.data.allData.seasoning_count,
            num: 1
        });
        wx.setStorageSync("select-menus", listMenus);
        wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 1500,
            mask: true
        })
        this.count()
    },
    //加入菜篮
    addShopcar() {
        let address = wx.getStorageSync('address');
        if (!address) {
            app.login();
            return;
        }
        let that = this;
        var fList = this.data.fList;
        var zList = this.data.zList;
        var listMenus = wx.getStorageSync('select-menus') || [];
        // 添加菜篮 循环参数
        let products = [];
        fList.forEach(item => {
            if (item.number > 0) {
                products.push({ product_id: item.id, shop_id: item.shop_id, num: item.number })
            }
        })
        zList.forEach((item) => {
            if (item.number > 0) {
                products.push({ product_id: item.id, shop_id: item.shop_id, num: item.number })
            }
        })
        console.log('products', products);
        if (products.length < 1) {
            wx.showToast({
                title: '您还未选择菜品',
                icon: 'none',
                duration: 1500,
                mask: true
            })
            return false;
        }
        this.editGoods({
            user_id: wx.getStorageSync("user_id"),
            products: products,
            cookbook_id: that.data.cookId,
        }, api.shoppingCartAdd).then((res) => {
            if (res.code == 200) {
                // 添加菜谱
                if (listMenus.length > 0) {
                    listMenus.forEach((item, index) => {
                        if (item.cookId == that.data.caiId) {
                            listMenus.splice(index, 1)
                        }
                    })
                }
                listMenus.push({
                    url: that.data.allData.url,
                    cookId: that.data.caiId,
                    name: that.data.allData.name
                });
                wx.setStorageSync("select-menus", listMenus);
                wx.showToast({
                    title: '加入成功',
                    icon: 'success',
                    duration: 1500
                })
                setTimeout(function () {
                    wx.navigateBack({
                        delta: 50
                    })
                    let pages = getCurrentPages();// 当前页的数据，
                    let prevPage = pages[pages.length - 2];// 上一页的数据，
                    prevPage.setData({//对A页面data中的参数进行赋值（记住A页面赋值是在B页面完成的）
                        noRefresh: true,
                    })
                }, 1000)
            } else {
                wx.showToast({
                    title: '添加失败，请稍后重试',
                    icon: 'none',
                    duration: 1500,
                    mask: true
                })
            }
        })





    },
    //获取相关菜谱
    getBooks(id) {
        http.request({
            url: api.getPidCookbookS,
            method: "POST",
            data: {
                id: id,
                page: 1,
                pagesize: 1000
            },
            success: (res) => {
                console.log(res)
                this.setData({
                    sameBook: res.data
                })
            }
        })
    },
    getAddressLength() {
        http.request({
            url: api.allAddress,
            method: "POST",
            data: {
                user_id: wx.getStorageSync("user_id")
            },
            success: (res) => {
                console.log(res)
                this.setData({
                    aLength: res.length
                })
            }
        })
    },
    onPageScroll: function (e) {
        // console.log(e.scrollTop)
        if (e.scrollTop > 300) {
            this.setData({
                showTop: false
            })
        } else {
            this.setData({
                showTop: true
            })
        }
    },
    goBack() {
        wx.navigateBack({
            delta: 1
        })
    },
    //商品详情页
    toDetail() {
        wx.navigateTo({
            url: '/pages/detail/detail?id=' + e.currentTarget.dataset.id,
        })
    },
    count() {
        var newList = wx.getStorageSync("select-menus") || []
        newList.filter((item) => {
            return item.num
        })
        var count = 0
        newList.map((item) => {
            count += item.num
        })
        this.setData({
            num: count
        })
    },
    toLogin() {
        wx.hideTabBar({})
        wx.switchTab({
            url: '/pages/index/index',
        })
    },
    onLoad: function (options) {



        console.log('id', options.id)
        let is_auth = wx.getStorageSync('is_auth');
        let address = wx.getStorageSync('address');
        if (is_auth) {
            this.setData({
                is_auth: true
            })
        }
        let s_height = wx.getSystemInfoSync().windowHeight;
        this.getOneCookbook(options.id, address.latitude, address.longitude);

        // console.log("==========================================")
        // console.log('options', options)
        this.setData({ "caiId": options.id })
        if (options.signShop) {
            this.setData({
                signShop: true
            })
        }



        var list = wx.getStorageSync("shoucang-list2") || []
        var list = list.filter((item) => {
            return (item.cookbookId == options.id && item.userId == wx.getStorageSync("user_id"))
        })
        if (list.length == 0) {
            this.setData({
                url: config.imgUrl + "/images/index/xing2.png"
            })
        } else {
            this.setData({
                url: config.imgUrl + "/images/index/xing1.png"
            })
        }




    },
    getOneCookbook(id, lat, lng) {
        console.log(api.getOneCookbooks)
        wx.showLoading({
            title: '加载中',
        })
        http.request({
            url: api.getOneCookbooks,
            method: "POST",
            data: {
                id: id,
                lat: lat,
                lng: lng
            },
            success: (res) => {
                console.log('4444444444444')
                wx.hideLoading()
                console.log(res)
                let that = this;
                that.upDownSilde()
                if (res.error_code == 50003) {
                    wx.showToast({
                        title: '当前菜谱不存在哦',
                        duration: 1500,
                        mask: true,
                        icon: 'none'
                    })
                    return false;
                } else if (res.error_code == 50004) {
                    this.setData({
                        empty: false
                    })
                    return false;
                }
                const data = res.data,
                    zList = [],
                    fList = [],
                    cookId = 0;
                // cookId=data.id
                if (data.list) {
                    if (data.list.length == 0) {
                        this.setData({
                            nearBool: false,
                            zbool: false,
                            iscontent: true,
                            booktab: false,
                            notuijian: true
                        })
                    } else {
                        if (data.list.主料) {
                            data.list.主料.forEach((ele) => {
                                ele.number = 1
                                zList.push(ele)
                            })
                        }

                        if (data.list.辅料) {
                            data.list.辅料.forEach((ele) => {
                                ele.number = 0
                                fList.push(ele)
                            })
                        }
                        console.log("333333333")
                        console.log(zList)
                        console.log(fList)
                        that.setData({
                            zList: zList,
                            fList: fList,
                            cookId: data.id,
                            istuijian: true,
                            recommend: data.recommend
                        })
                    }

                } else {
                    this.setData({
                        nearBool: false,
                        zbool: false,
                        iscontent: true,
                        booktab: false,
                        notuijian: true
                    })
                }

                let allData = Object.assign({}, data);
                let {
                    ingredients,
                    nutrition,
                    step
                } = data;
                if (ingredients) { //主辅料
                    ingredients = JSON.parse(ingredients);
                    that.setData({
                        ingredients
                    })
                }
                // 图表数据
                if (nutrition) {
                    nutrition = JSON.parse(nutrition);
                    let aaa = {}
                    for (let i in nutrition) {
                        aaa[i] = parseInt(nutrition[i])
                    }
                    if (Object.keys(aaa).length == 0) {
                        that.setData({
                            nutrition: []
                        })
                    } else {

                        that.setData({
                            nutrition: aaa
                        })
                    }

                }

                //步骤
                if (step) {
                    step = JSON.parse(step);
                    let arr = []
                    Object.keys(step).forEach(function (key) {
                        arr.push(step[key])
                    });
                    that.setData({
                        step: arr
                    })
                }

                //评分
                let grade = 0;
                grade = Math.floor(allData.grade / 2);
                //标题
                wx.setNavigationBarTitle({
                    title: allData.name,
                })
                that.setData({
                    allData,
                    grade
                });
            }
        });
    },
    //上下滑动确定营养普 用料 做法对应到顶部的高度
    upDownSilde(e) {
        let that = this;
        let hightArr = [];
        let navName = this.data.navName;
        for (let i = 0; i < navName.length; i++) {
            //获取元素所在位置
            let query = wx.createSelectorQuery();
            let idView = "#NAV" + i;
            query.select(idView).boundingClientRect()
            query.exec(function (res) {
                let top = res[0].top - 68;
                hightArr.push(top);
                that.setData({
                    hightArr: hightArr
                })
                console.log('hightArr', hightArr)
            });
        }
    },
    //跳转到地标商城
    redirctLink() {
        wx.redirectTo({
            url: "/pages/landmark/landmark",
        })
    },
    //点击顶部tab
    clickVideoTab(e) {
        const tabIndex = e.currentTarget.dataset.index;
        let isLeft = this.data.isLeft;
        isLeft = tabLeft[tabIndex]
        this.setData({
            isLeft,
            tabIndex
        })
    },
    //回到顶部
    scrollToTop() {
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: 0
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },
    scroll(e) {
        console.log(e)
        let scrollTop = e.detail.scrollTop;
        let scrollArr = this.data.hightArr;
        this.setData({
            scrollTop
        })

        if (scrollTop >= 0 && scrollTop < scrollArr[0]) {
            this.setData({
                scrollIndex: null,
                isLeft: null
            })

        } else if (scrollTop >= scrollArr[0] && scrollTop <= scrollArr[1]) {
            this.setData({
                scrollIndex: 0,
                isLeft: tabLeft[0]
            })
        } else if (scrollTop >= scrollArr[1] && scrollTop <= scrollArr[2]) {
            this.setData({
                scrollIndex: 1,
                isLeft: tabLeft[1]
            })
        } else if (scrollTop >= scrollArr[2]) {
            this.setData({
                scrollIndex: 2,
                isLeft: tabLeft[2]
            })

        }


    },

    onShow: function () {
        this.getAddressLength()
        var that = this
        wx.getSystemInfo({
            success(res) {
                console.log(res.model)
                if (res.model.indexOf("iPhone X") != -1) {
                    that.setData({
                        white: true
                    })
                }
            }
        })
        //获取已选菜谱num值
        this.count()
    },

    onShareAppMessage: function (res) {
        // console.log("点击了菜单11111111111111");

        let str = '味歌，改变买菜习惯：先选菜谱，后买菜！'
        // let id = res.target.dataset.id; //菜谱id
        // if (res.from === 'button') {
        //   console.log("来自页面内转发按钮");
        //   console.log(res.target);
        // } else {
        //   console.log("来自右上角转发菜单")
        //   console.log(res);
        // }
        // "/pages/video/video?typeShare=1&id=${this.data.caiId}"
        // 来自页面内转发按钮
        var content = {
            title: this.data.allData.title + '——' + str,
            imageUrl: this.data.allData.url,
            path: `/pages/index/index?redirect=/pages/video/video&typeShare=1&id=${this.data.caiId}`,
        }


        return content;
    },
    experience() {
        // 首页刷新
        this.setData({
            indexRefresh: true
        })
        setTimeout(() => {
            wx.navigateTo({
                url: '/pages/getDizhi/getDizhi?order=0&back=backHome'
            })
        }, 100);
    },
    onUnload() {
        // 传递参数 首页不刷新
        if (!this.data.indexRefresh) {
            let pages = getCurrentPages();// 当前页的数据，
            let prevPage = pages[pages.length - 2];// 上一页的数据，
            prevPage.setData({//对A页面data中的参数进行赋值（记住A页面赋值是在B页面完成的）
                noRefresh: true,
            })
        }

    }
});